import React, { Fragment } from 'react'
import { Tooltip } from 'antd'

export default class Clamp extends React.PureComponent {
  render() {
    const { content, length = 20 } = this.props
    return (
      <Fragment>
        {
          getStringLen(content) > length ? <Tooltip title={content}>
            <span>{clampString(content, length)}</span>
          </Tooltip> : content
        }
      </Fragment>
    )
  }
}

function getStringLen(string = '') {
  let len = 0
  for (let i = 0; i < string.length; i++) {
    if (string.charCodeAt(i) > 127 || string.charCodeAt(i) === 94) {
      len += 2
    } else {
      len += 1
    }
  }
  return len
}

function clampString(string = '', length) {
  let len = 0
  for (let i = 0; i < string.length; i++) {
    if (string.charCodeAt(i) > 127 || string.charCodeAt(i) === 94) {
      len += 2
    } else {
      len += 1
    }
    if (len >= length) {
      return string.substring(0, i) + '...'
    }
  }
  return string
}
